<template>
 <div>
    <el-tabs v-model="activeName" class="tabs linebox">
        <el-tab-pane name="1">
            <span slot="label"><i class="iconfont">&#xe621;</i> 综合监控汇总</span>
        </el-tab-pane>
        <el-tab-pane name="2">
            <span slot="label"><i class="iconfont">&#xe632;</i> 综合监控详情</span>
        </el-tab-pane>
    </el-tabs>
    <div class="search" v-if="activeName == '1'">
        <el-form  :model="formInline" inline size="small">
            <el-form-item label="类型">
                <el-select v-model="formInline.timeTp" placeholder="请选择" @change="handleChangeTimeType">
                <el-option label="按年" :value="1"></el-option>
                <el-option label="按月" :value="2"></el-option>
                <!-- <el-option label="按日" :value="3"></el-option> -->
                <el-option label="按用户自定义" :value="4"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="年" v-if="formInline.timeTp == 1">
                <el-date-picker
                v-model="formInline.timeSign"
                type="year"
                format="yyyy年"
                value-format="yyyy"
                placeholder="选择年">
                </el-date-picker>
            </el-form-item>

            <el-form-item label="月" v-if="formInline.timeTp == 2">
                <div class="date-box">
                <el-input prefix-icon="el-icon-date" style="width:220px" v-model="formInline.timeSign" readonly @focus="showDateBox = true"/>
                <div class="shape" v-show="showDateBox" @click="showDateBox = false"></div>
                <calendar v-show="showDateBox" class="date-con" :eventData="eventData" @month-select="handleSelectMonth" />
                </div>
            </el-form-item>  
            <el-form-item label="时间" v-if="formInline.timeTp == 4">
                <el-select v-model="formInline.timeId" placeholder="请选择">
                <el-option
                    v-for="item in dateList"
                    :key="item.id"
                    :label="`${ item.b_t } 至 ${ item.e_t }`"
                    :value="item.id">
                </el-option>
                </el-select>
            </el-form-item>  
            <el-form-item label="级别">
                <el-select v-model="formInline.leve" placeholder="请选择" class="form-item">
                    <el-option label="全部" :value="0"></el-option>
                    <el-option label="正常" :value="1"></el-option>
                    <el-option label="Ⅲ级" :value="2"></el-option>
                    <el-option label="Ⅱ级"  :value="3"></el-option>
                    <el-option label="Ⅰ级" :value="4"></el-option>
                </el-select>
            </el-form-item> 
            <el-form-item>
                <el-button type="primary" @click="getTreeTableData" icon="el-icon-search" >查询</el-button>
            </el-form-item>
            <el-form-item>
                <el-radio-group v-model="seeType" size="mini">
                    <el-radio-button label="0"><i class="iconfont">&#xeb94;</i></el-radio-button>
                    <el-radio-button label="1"><i class="iconfont">&#xe635;</i></el-radio-button>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <div>
            <el-button type="primary" size="small" @click="handleShowCalculation" icon="el-icon-connection">计算</el-button>
        </div>
    </div>        

    <div class="content boxWrapper" v-if="activeName == '1' && seeType == '0'" v-loading="tableLoading" element-loading-text="数据加载中，请稍后"
    element-loading-spinner="el-icon-loading">
        <el-table :data="tableData"  
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}" row-key="ID"
        :expand-row-keys="expandRow"
        border height="calc(100vh - 260px)" v-if="tableData.length > 0"> 
            <el-table-column prop="indexName" label="指标名称"></el-table-column>
            <el-table-column prop="time" label="评价日期" align="center"></el-table-column>
            <el-table-column prop="judgment" label="评价结果" align="center">
            <template slot-scope="scope"> 
                <el-tag type="info" v-if="scope.row.judgment == '无'" size="small">{{ scope.row.judgment }}</el-tag>

                <el-tag type="success" v-if="scope.row.judgment == '正常'" size="small">{{ scope.row.judgment }}</el-tag>

                <el-tag v-if="scope.row.judgment == '轻微异常' || scope.row.judgment == 'III级'" size="small">{{ scope.row.judgment }}</el-tag>

                <el-tag type="warning" v-if="scope.row.judgment == '一般异常' | scope.row.judgment == 'II级'" size="small">{{ scope.row.judgment }}</el-tag>

                <el-tag type="danger" v-if="scope.row.judgment == '严重异常' || scope.row.judgment == 'I级'" size="small">{{ scope.row.judgment }}</el-tag>
            
                <i class="iconfont" v-if="scope.row.is_BOTTOM == 1" style="font-size: 16px; color:#409eff;margin-left:10px" @click="handleShowDrawer(scope.row)">&#xe611;</i>
            </template>
            </el-table-column>
            <el-table-column prop="judemengtIllustrate" label="评判说明" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="check_" label="审核状态" align="center">
            <template slot-scope="scope">
                <el-select
                        size="small"
                        style="width:120px"
                        :value="scope.row.check_"
                        @change="cellDataChange(scope.row, {key:'check'}, $event)" 
                        placeholder="请选择"
                        v-show="scope.row.check_ != null"
                    >
                    <el-option label="通过" :value=1></el-option>
                    <el-option label="未通过" :value=0></el-option>
                    </el-select>
            </template>
            </el-table-column>
            <el-table-column prop="checkUser" label="审核用户" align="center"></el-table-column>
            <el-table-column prop="mess" label="详情" align="center">
                <template #default="{row}">
                    <span v-html="formatResult(row.mess)"></span>
                </template>
            </el-table-column>
        </el-table>
        <noData showData v-if="tableData.length == 0"/>
    </div>
    <div v-if="activeName == '1' && seeType == '1'" class="orgTree">
        <vue2-org-tree
            :data="treeData.data"
            :collapsable="collapsable"
            :render-content="renderContent"
            name="organ"
            :horizontal="true"
            @on-expand="onExpand"
            @on-node-click="onNodeClick" v-if="tableData.length > 0">
        </vue2-org-tree>
        <noData showData v-if="tableData.length == 0"/>
    </div>
    <comprehensiveData v-if="activeName == '2'" :stationId="stationId" @handleShowCount="handleShowCount"/>

    <onlineDrawer :search-data="drawerSearchData" isComprehensive :visible="drawerDialogVisible" @handleCloseDatas="handleCloseDatas"/>

    <el-dialog title="计算" :visible.sync="calculatonDialog" v-dialogDrag width="400px">
        <el-form  :model="formCalculationData" class="demo-form-inline" size="small" label-width="80px">
          <el-form-item label="类型">
            <el-select v-model="formCalculationData.timeTp" placeholder="请选择">
              <el-option label="按年" :value="1"></el-option>
              <el-option label="按月" :value="2"></el-option>
              <el-option label="按用户自定义" :value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年" v-if="formCalculationData.timeTp == 1">
            <el-date-picker
              v-model="formCalculationData.timeSign"
              type="year"
              format="yyyy年"
              value-format="yyyy"
              placeholder="选择年">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="月" v-if="formCalculationData.timeTp == 2">
            <el-date-picker
              v-model="formCalculationData.timeSign"
              type="month"
              format="yyyy年MM月"
              value-format="yyyy-MM"
              placeholder="选择月">
            </el-date-picker>
          </el-form-item>


          <el-form-item label="自定义" v-if="formCalculationData.timeTp == 4">
            <el-date-picker
              v-model="formCalculationData.b_Time"
              type="date"
              format="yyyy年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              @change="handleChangeDate"
              placeholder="开始时间"/>
            <div>至</div>
           <el-date-picker
              v-model="formCalculationData.e_Time"
              type="date"
              format="yyyy年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              @change="handleChangeDate"
              placeholder="结束时间"/>
          </el-form-item>
        </el-form>
        <div class="btnGroup">
          <el-button type="success" @click="handleCalculationClick(0)" size="small" icon="el-icon-connection">补算</el-button>
          <el-button type="primary" @click="handleCalculationClick(1)" size="small" icon="el-icon-refresh-right">重算</el-button>
        </div>
      </el-dialog>

    
  </div>
</template>

<script>
import {getIndexByStationZH,getCalcRecordList,getUserCustomize,scuRemIndexResultCheck,CALCIndexByStation} from '@/api/https'
import bus from '@/utils/eventBus.js';
import onlineDrawer from '@/components/page/monitoring/onlineDrawer.vue';
import comprehensiveData from '@/components/page/monitoring/comprehensiveData.vue';
import noData from '@/components/base/noData.vue';
import calendar from '@/components/page/monitoring/calendar.vue'
export default ({
    components:{onlineDrawer,comprehensiveData,noData,calendar},
    name:'comprehensive',
    data(){
        return {
            stationId:sessionStorage.getItem("stationId"),
            activeName:'1',
            formInline:{},
            seeType:'0',
            tableData:[],
            expandRow:[],
            formData:{},
            treeData: {
                basicInfo: { id: null, label: "---null" },
                basicSwitch: false,
                data: {},
            },
            collapsable: true,
            tableLoading:false,
            drawerSearchData:{},
            drawerDialogVisible:false,  
            dateList:[],
            showDateBox:false, 
            eventData:[],
            calculatonDialog:false,
            formCalculationData:{
                timeTp:1
            }
        }
    },
    mounted(){
        this.initBasin()
        this.getDateForm()
        this.getTreeTableData()
        this.onGetCalcRecordList()
    },
    deactivated(){
       bus.$off('station-changed', this.handleStationChanged);
    },
    beforeDestroy(){
       bus.$off('station-changed', this.handleStationChanged);
    },
    activated(){
        this.initBasin()
        const newStationId = sessionStorage.getItem("stationId");
        if (this.stationId != newStationId) {
           this.stationId = newStationId;
           this.getTreeTableData()
           this.onGetCalcRecordList()
        }else{
            
        }
    },
    methods:{
        initBasin() {
            bus.$emit('showBasin', true);
            bus.$off('station-changed', this.handleStationChanged);
            bus.$on('station-changed', this.handleStationChanged);
        },
        handleStationChanged(newStationId, targetRoute) {
            if (!targetRoute || targetRoute === this.$route.name) {
                this.stationId = newStationId;
                this.getDateForm()
                this.getTreeTableData()
                this.onGetCalcRecordList()
            }
        },
        getDateForm(){
            const toDay = new Date()
            const sevenDaysAgo = new Date(toDay);
            sevenDaysAgo.setDate(toDay.getDate() - 7);
            this.formInline = {
                timeTp:2,
                timeSign:'2025-05',
                leve:0,
                station_ID:this.stationId,
                categroy:1,
                b_Time:'',
                e_Time:'',
                tp:0,
            }
        },
        getTreeTableData(){
            this.tableLoading = true
            getIndexByStationZH(this.formInline).then(res=>{
                if(res.isSuccess && res.data && res.data.length > 0){
                    this.tableData = res.data
                    const id = res.data[0].ID.toString()
                    this.expandRow = [id]
                    // 评价结果树状图数据
                    this.treeData.data = res.data[0]
                    this.toggleExpand(res.data[0])
                    this.tableLoading = false
                }else{
                    this.tableLoading = false
                    this.tableData = []
                    this.treeData.data = {}
                }
            })
        },
        toggleExpand(data, val) {
            // 默认展开三级
            var _this = this;
            if (Array.isArray(data)) {
                data.forEach(function(item) {
                    _this.$set(item, "expand", true);
                });
            } else {
                this.$set(data, "expand", true);
                if (data.children) {
                    _this.toggleExpand(data.children, true);
                }
            }
        },
        renderContent(h, data) {
            return (
            <div style="min-width:200px;">
                <div>
                    <el-tooltip class="item" effect="dark" content="正常" placement="top-start">
                        <i class="iconfont pointStatus greenText" v-show={data.judgment == '正常'}>&#xe633;</i>
                    </el-tooltip>

                    <el-tooltip class="item" effect="dark" content="Ⅰ级" placement="top-start">
                       <i class="iconfont pointStatus redText" v-show={data.judgment == 'I级' }>&#xe633;</i>
                    </el-tooltip>

                    <el-tooltip class="item" effect="dark" content="Ⅱ级" placement="top-start">
                       <i class="iconfont pointStatus orangeText" v-show={data.judgment == 'II级'}>&#xe633;</i>
                    </el-tooltip>

                    <el-tooltip class="item" effect="dark" content="Ⅲ级" placement="top-start">
                        <i class="iconfont pointStatus blueText" v-show={data.judgment == 'III级'}>&#xe633;</i>
            
                    </el-tooltip>
                    <span class="pointStatus-text">{data.indexName}</span>
                <div class="numberBox" v-show={data.is_BOTTOM == 0}>
                    <el-tooltip class="item" effect="dark" content="Ⅰ级" placement="top-start">
                        <span class="pointNumber redText">
                    <i class="pointStatus1" style="background:#f00"></i>{data.abnormal3}</span>
                    </el-tooltip>

                    <el-tooltip class="item" effect="dark" content="Ⅱ级" placement="top-start">
                        <span class="pointNumber orangeText" >
                    <i class="pointStatus1" style="background:#fc8452"></i>{data.abnormal2}</span>
                    </el-tooltip>

                    <el-tooltip class="item" effect="dark" content="Ⅲ级" placement="top-start">
                        <span class="pointNumber blueText">
                    <i class="pointStatus1" style="background:#0b6ddd"></i>{data.abnormal1}</span>
                    </el-tooltip>


                    <el-tooltip class="item" effect="dark" content="正常" placement="top-start">
                       <span class="pointNumber greenText">
                    <i class="pointStatus1" style="background:#03b009"></i>{data.normal}</span> 
                    </el-tooltip>    
                </div>   
                </div>
            </div>
            )
        },
        onExpand(e, data) {
            if ("expand" in data) {
                data.expand = !data.expand;
                if (!data.expand && data.children) {
                this.collapse(data.children);
                }
            } else {
                this.$set(data, "expand", true);
            }
        },
        collapse(list) {
            var _this = this;
            list.forEach(function(child) {
                if (child.expand) {
                child.expand = false;
                }
                child.children && _this.collapse(child.children);
            });
        },
        onNodeClick(ev,data){
            if(data.is_BOTTOM == 1){
            // 如果是最后一级，调评价数据和变位图接口 
              this.handleShowDrawer(data)
            }
        },
        formatResult(text) {
           if (text === null || text === undefined || typeof text !== 'string') {
            return '';
          }
          // 定义标签到颜色的映射
          const tagToColor = {
            'g': '#03b009',    // 绿色
            'b': '#0b6ddd',      // 蓝色
            'y': '#edb140',    // 黄色
            'o': '#fc8452',    // 橙色
            'r': '#f00'        // 红色
          };
          

          return text.replace(/<([gbyor])>(.*?)<\/\1>/g, (match, tag, content) => {
            const color = tagToColor[tag] || 'inherit';
            return `<span class="tableNumber" style="color: ${color};">${content}</span>`;
          });
        },

        handleShowDrawer(data){
            let b_Time,e_Time
            if(this.formInline.timeId && this.formInline.timeTp == 4){
                this.dateList.forEach(item=>{
                    if(item.id == this.formInline.timeId){
                        b_Time = item.b_TIME
                        e_Time = item.e_TIME
                    }
                })
            }
            this.drawerSearchData = {
                ...this.formInline,
                indeX_ID:data.INDEX_ID,
                b_Time:b_Time || '',
                e_Time:e_Time || ''
            }
            this.drawerDialogVisible = true
        },
        handleCloseDatas(){
            this.drawerDialogVisible = false
            this.drawerSearchData = {}
        },
        handleShowCount(){
            this.$emit('handleShowCount')
        },
        handleChangeTimeType(val){
            const _d = {...this.formInline}
            _d.timeSign = ''
            this.formInline = {..._d}
            if(val == 4){
                getUserCustomize(this.stationId).then(res=>{
                    if(res.isSuccess){
                        this.dateList = res.data || []
                    }
                })
            }
            if(val == 2){
                this.onGetCalcRecordList()
            }
        },
        handleSelectMonth(date){
          this.formInline.timeSign = `${date.year}-${date.month}`
          this.showDateBox = false
        },
        onGetCalcRecordList(){
            getCalcRecordList({
                station_id:this.stationId,
                timeTp:2
            }).then(res=>{
                if(res.isSuccess){
                    this.eventData = res.data || []
                }
            })
        },
        cellDataChange(row, column, cellValue) {
            if(column.key == 'check'){
                scuRemIndexResultCheck({
                    ID:row.id || row.ID,
                    CHECK:cellValue,
                    STATION_ID:this.stationId
                }).then(res=>{
                    if(res.isSuccess){
                        this.$message.success('操作成功！')
                    }else{
                    this.$message.error(res.errorMessage)
                    }
                })
            }
        },
        handleShowCalculation(){
            this.calculatonDialog = true
        },
        handleCalculationClick(num){
            let _data = {}
            if(this.formCalculationData.timeTp == 4){
                _data = {
                    station_ID:this.stationId,
                    timeSign:'',
                    timeTp:this.formCalculationData.timeTp,
                    categroy:1,
                    b_Time:this.formCalculationData.b_Time,
                    e_Time:this.formCalculationData.e_Time,
                    tp:0,
                    calcTp:num
                }
            }else{
                _data = {
                    station_ID:this.stationId,
                    timeSign:this.formCalculationData.timeSign,
                    timeTp:this.formCalculationData.timeTp,
                    categroy:1,
                    b_Time:'',
                    e_Time:'',
                    tp:0,
                    calcTp:num
                }
            }
            CALCIndexByStation(_data).then(res=>{
                if(res.isSuccess){

                }else{
                    this.$message.error(res.errorMessage)
                }
            })
                this.calculatonDialog = false
                this.formCalculationData = {
                    timeTp:1
                }
        },
    }
   
})
</script>


<style scoped lang="scss">
.tabs{
    padding:0 20px;
}
.linebox{
    background: #fff;
    border-top-right-radius: 5px;
    border-top-left-radius: 5px;
}
.search{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    background: #fff;
    border-bottom-right-radius: 5px;
    border-bottom-left-radius: 5px;
    padding:0 20px;
    box-sizing: border-box;
}
.content{
    margin-top:10px;
    padding:10px;
    box-sizing: border-box;
}
.orgTree{
    background: url('../../assets/image/orgBG.png') no-repeat center #fff;
    height: calc(100vh - 240px);
    overflow-x: auto;
    overflow-y: auto;
    background-size: 100% 100%;
    text-align: center;
    box-sizing: border-box;
    margin-top:10px;
    ::v-deep .org-tree-node-label .org-tree-node-label-inner{
      background: #fefefe;
      color:#333;
      box-shadow: 0 1px 5px rgba(0, 73, 111, 0.15);
    }
}
::v-deep .pointStatus{
  display:inline-block;
  font-size:18px;
  vertical-align:middle;
  margin-right: 10px;
}
::v-deep .pointNumber{
  font-size:14px;
  line-height:30px;
  font-weight:bold;
}
::v-deep .numberBox{
  background: #f4f4f4;
  border-radius:8px;
  margin-top: 10px;
}
::v-deep .pointStatus1  {
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  margin:0 2px 0 18px;
  font-size: 12px;
  vertical-align: middle;
}
::v-deep .pointStatus-text{
  font-size: 14px;
  font-weight: bold;
  line-height: 24px;
  vertical-align: middle;
}
::v-deep .org-tree-container{
  background: none !important;;
}
::v-deep .tableNumber{
  font-weight: bold;
  padding:0 2px;
  font-size: 14px;
}
.date-box{
  position: relative;
  .shape{
    position: fixed;
    top:0;
    left:0;
    right:0;
    bottom: 0;
    z-index: 2000;
  }
  .date-con{
    position:absolute;
    top:40px;
    left:0;
    transform-origin: center top;
    z-index: 2001;
  }
}
</style>

